package com.bk.bookviews.service.impl;

import com.bk.bookviews.common.Pagination;
import com.bk.bookviews.domain.Comment;
import com.bk.bookviews.domain.CommentExample;
import com.bk.bookviews.domain.UserInfo;
import com.bk.bookviews.exception.BusinessException;
import com.bk.bookviews.exception.BusinessExceptionEnum;
import com.bk.bookviews.mapper.CommentMapper;
import com.bk.bookviews.service.CommentService;
import com.bk.bookviews.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommentServiceIMpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Comment selectComment(Integer id) {
        return commentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveComment(Comment comment, String token) {
        UserInfo userInfo = (UserInfo) redisUtil.get(token);
        if (userInfo == null){
            throw new BusinessException(BusinessExceptionEnum.LOGON_FAILURE);
        }
        comment.setUserId(userInfo.getUserId());
        comment.setCreateTime(new Date());
        commentMapper.insertSelective(comment);
    }

    @Override
    public Pagination selectCommentList(Comment comment) {
        CommentExample example = new CommentExample();
        CommentExample.Criteria criteria = example.createCriteria();
        if (comment.getUserId() != null){
            criteria.andUserIdEqualTo(comment.getUserId());
        }
        if (comment.getScenicId() != null){
            criteria.andScenicIdEqualTo(comment.getScenicId());
        }
        example.setOrderByClause("create_time desc");
        return new Pagination(commentMapper.selectByExample(example));
    }

    @Override
    public void editSave(Comment comment) {
        commentMapper.updateByPrimaryKeySelective(comment);
    }

    @Override
    public void delete(Integer id) {
        commentMapper.deleteByPrimaryKey(id);
    }
}
